// hooks/useRequest/cache.ts
import { CacheData } from './types';

// 缓存存储
const cacheStore = new Map<string, CacheData>();

/**
 * 生成缓存键
 * @param url 请求URL
 * @param params 请求参数
 * @returns 缓存键
 */
export const generateCacheKey = (url: string, params?: any): string => {
    return `${url}:${params ? JSON.stringify(params) : ''}`;
};

/**
 * 设置缓存
 * @param key 缓存键
 * @param data 缓存数据
 * @param cacheTime 缓存时间（毫秒）
 */
export const setCache = <T>(key: string, data: T, params: any, cacheTime: number): void => {
    if (cacheTime <= 0) return;

    const cacheData: CacheData<T> = {
        data,
        timestamp: Date.now(),
        params
    };

    cacheStore.set(key, cacheData);

    // 设置过期自动清理
    setTimeout(() => {
        if (cacheStore.has(key)) {
            cacheStore.delete(key);
        }
    }, cacheTime);
};

/**
 * 获取缓存
 * @param key 缓存键
 * @param cacheTime 缓存时间（毫秒）
 * @returns 缓存数据或undefined
 */
export const getCache = <T>(key: string, cacheTime: number): T | undefined => {
    if (cacheTime <= 0) return undefined;
	

    const cacheData = cacheStore.get(key) as CacheData<T> | undefined;
    if (!cacheData) return undefined;

    // 检查缓存是否过期
    const now = Date.now();
    if (now - cacheData.timestamp > cacheTime) {
        cacheStore.delete(key);
        return undefined;
    }

    return cacheData.data;
};

/**
 * 清除特定缓存
 * @param key 缓存键
 */
export const clearCache = (key: string): void => {
    cacheStore.delete(key);
};

/**
 * 清除所有缓存
 */
export const clearAllCache = (): void => {
    cacheStore.clear();
};

/**
 * 根据URL前缀清除缓存
 * @param urlPrefix URL前缀
 */
export const clearCacheByUrlPrefix = (urlPrefix: string): void => {
    for (const key of cacheStore.keys()) {
        if (key.startsWith(urlPrefix)) {
            cacheStore.delete(key);
        }
    }
};

/**
 * 获取缓存数据的参数
 * @param key 缓存键
 * @returns 参数对象
 */
export const getCacheParams = (key: string): any => {
    const cacheData = cacheStore.get(key);
    return cacheData?.params;
}; 